import 'package:get/get.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_helper_account.dart';
import 'package:inmotion_pro/pages/mixin/bluetooth_mixin.dart';
import 'package:inmotion_pro/pages/mixin/realtime_info_mixin.dart';
import 'package:inmotion_pro/pages/mixin/web_view_mixin.dart';
import 'package:inmotion_pro/pages/models/settting_item_model.dart';
import 'package:inmotion_pro/service/vehicle_connection_service.dart';
import 'package:inmotion_pro/utils/string_util.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

import '../../../../l10n/local.dart';
import '../../../../routes/app_routes.dart';
import '../../../../service/global_service.dart';
import '../../../mixin/cache_mixin.dart';
import '../../../mixin/vehicle_type_mixin.dart';
import '../../../models/user_model.dart';
import 'state.dart';

class AccountSecurityController extends GetxController
    with WebViewMixin, CacheMixin, RealtimeInfoMixin, BluetoothMixin {
  // 状态
  final AccountSecurityState state = AccountSecurityState();
  // 车辆类型
  final VehicleType _vehicleType = GlobalService.to.currentVehicleType;

  @override
  void onInit() {
    super.onInit();
    _reloadData();
  }

  _reloadData() {
    // 初始化功能列表
    state.itemList.value = _vehicleType.accountSecurityCellList();
    // 赋值用户信息
    state.userInfo.value = GlobalService.to.cacheUserInfo.value;
    // 赋值OnTap事件
    for (int i = 0; i < state.itemList.length; i++) {
      for (int j = 0; j < state.itemList[i].subItems.length; j++) {
        _setCellOnTap(state.itemList[i].subItems[j]);
      }
    }
  }

  // 设置页面cell点击事件
  _setCellOnTap(SettingRowModel model) async {
    if (model.title == local.email_address) {
      model.value = LxStringUtil.obscureEmail(state.userInfo.value.email);
      model.onTap = () {
        Get.toNamed(AppRoutes.VERIFY_ACCOUNT,
                arguments: SecurityType.updateEmail)
            ?.then((_) => _reloadData());
      };
    } else if (model.title == local.phone_number) {
      model.value = LxStringUtil.obscurePhone(state.userInfo.value.phone);
      model.onTap = () {
        Get.toNamed(AppRoutes.VERIFY_ACCOUNT,
                arguments: SecurityType.updatePhone)
            ?.then((_) => _reloadData());
      };
    } else if (model.title == local.update_password) {
      model.onTap = () {
        Get.toNamed(AppRoutes.VERIFY_ACCOUNT, arguments: SecurityType.resetPwd);
      };
    } else if (model.title == local.bind_social_account) {
      model.onTap = () {
        Get.toNamed(AppRoutes.BIND_ACCOUNT);
      };
    } else if (model.title == local.remove_account) {
      model.onTap = () {
        Get.toNamed(AppRoutes.REMOVE_ACCOUNT);
      };
    }
  }

  // 退出登录
  logoutOnTap() {
    LxAlert.show(
      local.logout_tips,
      title: local.prompt_title,
      confirmCallback: (p0) {
        Loading.showLoading(null);
        ApiHelper()
            .logout(GlobalService.to.cacheUserInfo.value.token)
            .then((isSuccess) {
          if (isSuccess) {
            return cacheMixinUpdateUser(
              GlobalService.to.cacheUserInfo.value.uid,
              token: "",
              isSelected: false,
            ).then((_) async {
              // 停止轮询获取车辆实时数据
              return realtimeInfoMixinStopLoopToGetVehicleRealTimeData()
                  .then((success) async {
                if (success) {
                  VechileConnectionService.to.bluetoothConnectHelper!
                      .disconnect()
                      .then((_) {
                    Loading.showToast(local.logout_success);
                    // 退出登录
                    Get.offAllNamed(AppRoutes.LOGIN_REGISTER);
                  });
                } else {
                  Loading.showError(local.logout_failed);
                }
              });
            });
          }
          throw Exception(local.logout_failed);
        }).catchErrorHandler();
      },
      confirmTitle: local.confirm,
      cancelTitle: local.cancel,
    );
  }
}
